package com.example.base_kotlin_xml.model

import android.content.Context
import androidx.lifecycle.viewModelScope
import com.example.base_kotlin_xml.api.MainApiService
import com.example.base_kotlin_xml.model.repository.TestRepository
import com.example.base_model.api.ApiService
import com.example.base_model.bean.BaseHttpPageBean
import com.example.base_model.bean.SearchBean
import com.example.base_model.bean.SearchPostBean
import com.example.base_model.bean.general.DataMergeBean
import com.example.base_model.bean.general.TestRequest
import com.example.base_model.mvvm.BaseViewModel
import com.example.base_model.network.download.DownloadManager
import com.example.base_model.network.load.LoadingStrategy
import com.example.base_model.network.load.LoadingUiState
import com.example.base_model.network.request_param.ListBeanParamInterface
import com.example.base_model.network.result.BaseResult
import dagger.hilt.android.lifecycle.HiltViewModel
import kotlinx.coroutines.flow.MutableStateFlow
import kotlinx.coroutines.flow.StateFlow
import kotlinx.coroutines.flow.asStateFlow
import kotlinx.coroutines.flow.collectLatest
import kotlinx.coroutines.launch
import javax.inject.Inject

/**
 * @Author jiangKunKun
 * @CreateDate 2025/7/30
 * @Description
 * @SpittingGrooves
 */

data class NetworkUiState(
    override val loadingGroups: Map<LoadingStrategy, Int> = emptyMap(),

    val aisleCodeResult: BaseResult<String> = BaseResult.IDLE(),
    val searchResult: BaseResult<BaseHttpPageBean<SearchBean>> = BaseResult.IDLE(),
    val dataMergeBeanState: BaseResult<String> = BaseResult.IDLE(),
    val dataMergeBeanStateTwo: BaseResult<DataMergeBean> = BaseResult.IDLE(),
) : LoadingUiState {
    override fun copyWithLoading(groups: Map<LoadingStrategy, Int>): LoadingUiState {
        return this.copy(loadingGroups = groups)
    }
}
sealed interface NetworkIntent {
    data class Test1(val code: String, val str: String) : NetworkIntent
    data class Test2(val code: String) : NetworkIntent
    data class Test3(val code: String) : NetworkIntent
    data class Test4(val code: String) : NetworkIntent
    data class DownloadFile(val context: Context, val url: String, val path: String, val fileName: String) : NetworkIntent
}
@HiltViewModel
class NetworkViewModel @Inject constructor(
    private val apiService: ApiService,
    private val mainApiService: MainApiService,
    private val testRepository: TestRepository,
    private val downloadManager: DownloadManager,
): BaseViewModel() {

    /**
     * 页面统一是用一个
     */
    private val _uiState = MutableStateFlow(NetworkUiState())
    val uiState: StateFlow<NetworkUiState> = _uiState.asStateFlow()
    // 在 NetworkViewModel 中
    fun processIntent(intent: NetworkIntent) {
        when (intent) {
            is NetworkIntent.Test1 -> test1(intent.code, intent.str)
            is NetworkIntent.Test2 -> test2(intent.code)
            is NetworkIntent.Test3 -> test3(intent.code)
            is NetworkIntent.Test4 -> test4(intent.code)
            is NetworkIntent.DownloadFile -> downloadFile(intent.context, intent.url, intent.path, intent.fileName)
            // ... 处理其他意图
        }
    }
    fun test1(code: String, str : String){
        // 请求参数回调出去
        launchWithStateFlow(
            stateFlow = _uiState,
            loadingStrategy = LoadingStrategy.MAIN,
            stateUpdateBlock = { u, result ->
                u.copy(aisleCodeResult =  result) },
            block = { apiService.aisleCode(code) }
        )
    }


    fun test2(code: String){
        val searchPostBean = SearchPostBean("", "", 100, 1)
        val mutableMapOff = mutableMapOf<String, Any>(
            "userId" to "",
            "searchContent" to "",
            "pageSize" to "100",
            "pageNo" to 1
        )

        // 请求参数回调出去
        launchWithStateFlow(
            // 实体类参数
            stateFlow = _uiState,
            stateUpdateBlock = { u, result ->
                u.copy(searchResult = result)},
            block = { apiService.searchList(mutableMapOff) },
            transform = { result ->
                result?.apply {
                    list?.forEach {
                        it.name = "name修改后的数据"
                    }
                }
            }
        )
    }

    fun test3(code: String){
        // 请求参数回调出去
        launchWithStateFlow(
            // 列表参数
            stateFlow = _uiState,
            stateUpdateBlock = { u, result ->
                u.copy(dataMergeBeanState = result)},
            block = {
                apiService.beanList2(listOf(
                    TestRequest(name = "123456", password = "123456"),
                    TestRequest(name = "456789", password = "456789")
                ))
            }, requestParam = ListBeanParamInterface(
                listOf(
                    TestRequest(name = "123456", password = "123456"),
                    TestRequest(name = "456789", password = "456789")
                )
            )
        )
    }

    // 多数据源合并
    fun test4(code: String){
        launchWithStateFlow(
            stateFlow = _uiState,
            stateUpdateBlock = { u, result ->
                u.copy(dataMergeBeanStateTwo = result)},
            block = {
                testRepository.getAisleCode(code, "多数据源合并123", "多数据源合并456")
            }
        )
    }

    private val _downloadState = MutableStateFlow<DownloadManager.DownloadStatus>(DownloadManager.DownloadStatus.IDLE)
    val downloadState: StateFlow<DownloadManager.DownloadStatus> = _downloadState.asStateFlow()

    fun downloadFile(activity: Context,url: String, path: String, fileName: String) {
        viewModelScope.launch {
            downloadManager.downloadFile(url, path, fileName)
                .collectLatest { status ->
                    _downloadState.value = status
                }
        }
    }
}